package com.trailwalker.traceability.activity;

import com.trailwalker.JavaUtils.string.StringUtils;
import com.trailwalker.javafx.utils.style.StyleUtils;
import com.trailwalker.traceability.entitiy.body.ProcessRequestBody;
import com.trailwalker.traceability.entitiy.body.ProcessResponseBody;
import com.trailwalker.traceability.entitiy.enum_entity.ProcessType;
import com.trailwalker.traceability.service.ApiDataService;
import com.trailwalker.traceability.util.JfxUtils;
import com.trailwalker.traceability.widget.control.textfield.ScanTextFiled;
import io.reactivex.functions.Consumer;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.util.Callback;

/**
 * @author Trailwalker
 * @create 2021-11-12 13:08
 */
public class OutBoundActivity extends BaseActivity {

    private AnchorPane mApContent;
    private ScanTextFiled mTfId;
    private TextArea mTaNote;
    private Button mBtnComplete;
    private CheckBox mCbIsClearNote;
    private ObservableList<String> mScanedCodeList;
    private int mLastScanedCodeListSize;
    private ListView<String> mLvScanedCode;

    @Override
    protected void afterSuperCreate() {
        initLoad();
        initView();
        initData();
        initListener();
        onReady();
    }

    private void onReady() {

    }

    private void initListener() {
        if (mBtnComplete != null) {
            mBtnComplete.setOnMouseClicked(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent event) {
                    if (event.getButton().equals(MouseButton.PRIMARY)) {
                        trace();
                    }
                }
            });
        }

        if (mTfId != null) {
            mTfId.setOnScanFinishedListener(new ScanTextFiled.OnScanFinishedListener() {
                @Override
                public void onFinish(String value) {
                    if (StringUtils.isValid(value)) {
                        check(value);
                    }
                }
            });
        }

        if (mTaNote != null) {
            mTaNote.setOnKeyReleased(new EventHandler<KeyEvent>() {
                @Override
                public void handle(KeyEvent event) {
                    if (event.getCode() == KeyCode.ENTER) {
                        // 获得此时的光标位置。此位置为刚刚输入的换行符之后
                        int caretPosition = mTaNote.getCaretPosition();

                        // 如果已经按下的按键中包含 Control 键
                        if (!event.isControlDown()) {
                            // 如果输入的不是组合键 `Ctrl+Enter`，去掉换行符，然后将文本发送

                            // 获得输入文本，此文本包含刚刚输入的换行符
                            String text = mTaNote.getText();
                            // 获得换行符两边的文本
                            String front = text.substring(0, caretPosition - 1);
                            String end = text.substring(caretPosition);
                            mTaNote.setText(front + end);
                            /*----- 如果希望发送后保留输入框文本，需要只使用下面这行代码 -------*/
                            mTaNote.positionCaret(caretPosition - 1);

                            trace();
                        } else {
                            // 获得输入文本，此文本不包含刚刚输入的换行符
                            String text = mTaNote.getText();
                            // 获得光标两边的文本
                            String front = text.substring(0, caretPosition);
                            String end = text.substring(caretPosition);
                            // 在光标处插入换行符
                            mTaNote.setText(front + System.lineSeparator() + end);
                            // 将光标移至换行符
                            mTaNote.positionCaret(caretPosition + 1);
                        }
                    }
                }
            });
        }
    }

    private void check(String value) {
        mTfId.clear();
        ProcessRequestBody processRequestBody = new ProcessRequestBody();
        processRequestBody.setProNum(value);
        processRequestBody.setProcessName(ProcessType.OUTBOUND.getName());
        ApiDataService.getInstance().check(mApplication, processRequestBody, new Consumer<ProcessResponseBody>() {
            @Override
            public void accept(ProcessResponseBody processResponseBody) throws Exception {
                mTfId.setText(value);
                mTaNote.requestFocus();
            }
        });
    }

    private void trace() {
        if (validate()) {
            String id = mTfId.getText();
            String remark = mTaNote.getText();
            ProcessRequestBody processRequestBody = new ProcessRequestBody();
            processRequestBody.setProNum(id);
            processRequestBody.setProcessName(ProcessType.OUTBOUND.getName());
            processRequestBody.setRemark(remark);
            ApiDataService.getInstance().trace(mApplication, processRequestBody, new Consumer<ProcessResponseBody>() {
                @Override
                public void accept(ProcessResponseBody processResponseBody) throws Exception {
                    mTfId.clear();
                    if (mCbIsClearNote.isSelected()) {
                        mTaNote.clear();
                    }
                    mTfId.requestFocus();
                    addScanedCode(id);
                }
            });
        } else {
            JfxUtils.showShortToast(mApplication.getStage(), "请输入正确的数据");
        }
    }

    private void addScanedCode(String id) {
        if (mScanedCodeList.size() >= mLastScanedCodeListSize) {
            mScanedCodeList.remove(0);
        }
        mScanedCodeList.add(id);
        mLvScanedCode.scrollTo(mScanedCodeList.size() - 1);
    }

    private boolean validate() {
        String id = mTfId.getText();
        if (StringUtils.isEmpty(id)) {
            return false;
        }
        return true;
    }

    private void initData() {

    }

    private void initView() {
        BorderPane bpContent = new BorderPane();
        mApContent.getChildren().add(bpContent);
        mAdaptUtils.setMatchParentAnchorPane(bpContent);

        HBox hbTitle = new HBox();
        bpContent.setTop(hbTitle);
        hbTitle.setAlignment(Pos.CENTER);
        mAdaptUtils.setScaleHeight(hbTitle, 150);

        Label lblTitle = new Label();
        hbTitle.getChildren().add(lblTitle);
        lblTitle.setText(ProcessType.OUTBOUND.getName());
        mAdaptUtils.setScaleTextSize(lblTitle, 40);
        StyleUtils.setTextColor(lblTitle, "#000000");

        initCenterView(bpContent);

        initRightView(bpContent);
    }

    private void initRightView(BorderPane bpContent) {
        BorderPane bpRight = new BorderPane();
        bpContent.setRight(bpRight);
        AnchorPane.setTopAnchor(bpRight, 0.0);
        AnchorPane.setRightAnchor(bpRight, 0.0);
        AnchorPane.setBottomAnchor(bpRight, 0.0);
        StyleUtils.setBackgroundColor(bpRight, "#f2f2f2");

        mAdaptUtils.setScaleWidth(bpRight, 350);

        HBox hbRightTitle = new HBox();
        bpRight.setTop(hbRightTitle);
        hbRightTitle.setAlignment(Pos.CENTER);
        mAdaptUtils.setScaleHeight(hbRightTitle, 60);

        Label mLblRightTitle = new Label();
        hbRightTitle.getChildren().add(mLblRightTitle);
        mLblRightTitle.setText("已完成产品id列表(最近" + mLastScanedCodeListSize + "个)");
        StyleUtils.setTextColor(mLblRightTitle, "#000000");
        mAdaptUtils.setScaleTextSize(mLblRightTitle, 25);

        mLvScanedCode = new ListView<>(mScanedCodeList);
        bpRight.setCenter(mLvScanedCode);
        mLvScanedCode.setPadding(javafx.geometry.Insets.EMPTY);
        mLvScanedCode.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
            @Override
            public ListCell<String> call(ListView<String> param) {

                ListCell<String> listCell = new ListCell<String>() {
                    @Override
                    protected void updateItem(String item, boolean empty) {
                        super.updateItem(item, empty);

                        HBox hbItemContainer = new HBox();
                        mAdaptUtils.setScaleHeight(hbItemContainer, 40);
                        hbItemContainer.setAlignment(Pos.CENTER);

                        if (!empty) {
                            HBox hbIdContainer = new HBox();
                            hbItemContainer.getChildren().add(hbIdContainer);
                            hbIdContainer.setAlignment(Pos.CENTER);
                            HBox.setHgrow(hbIdContainer, Priority.ALWAYS);

                            Label lblId = new Label();
                            hbIdContainer.getChildren().add(lblId);
                            StyleUtils.setTextColor(lblId, "#000000");
                            mAdaptUtils.setScaleTextSize(lblId, 25);
                            lblId.setText(item);
                        }

                        this.setGraphic(hbItemContainer);
                    }
                };
                listCell.setPadding(Insets.EMPTY);
                return listCell;
            }
        });
    }

    private void initCenterView(BorderPane bpContent) {
        VBox vbCenter = new VBox();
        bpContent.setCenter(vbCenter);
        vbCenter.setAlignment(Pos.CENTER);
        vbCenter.setSpacing(mAdaptUtils.getScale(20));

        HBox hbGpContainer = new HBox();
        vbCenter.getChildren().add(hbGpContainer);
        hbGpContainer.setAlignment(Pos.CENTER);

        GridPane gpContainer = new GridPane();
        hbGpContainer.getChildren().add(gpContainer);
        gpContainer.setAlignment(Pos.CENTER);
        gpContainer.setHgap(mAdaptUtils.getScale(20));
        gpContainer.setVgap(mAdaptUtils.getScale(20));
        ColumnConstraints column1 = new ColumnConstraints();
        column1.setHalignment(HPos.RIGHT);
        gpContainer.getColumnConstraints().add(column1);
        ColumnConstraints column2 = new ColumnConstraints();
        column2.setHalignment(HPos.LEFT);
        gpContainer.getColumnConstraints().add(column2);

        mTfId = getTextFiled("ID:", gpContainer, 0);

        Label lblNote = new Label();
        gpContainer.add(lblNote, 0, 1);
        lblNote.setText("备注");
        StyleUtils.setTextColor(lblNote, "#000000");
        mAdaptUtils.setScaleTextSize(lblNote, 20);

        mTaNote = new TextArea();
        gpContainer.add(mTaNote, 1, 1);
        mAdaptUtils.setScaleHeight(mTaNote, 150);
        mAdaptUtils.setScaleWidth(mTaNote, 400);
        mAdaptUtils.setScaleTextSize(mTaNote, 22);
        mTaNote.setWrapText(true);

        HBox hbCheckBoxContainer = new HBox();
        vbCenter.getChildren().add(hbCheckBoxContainer);
        hbCheckBoxContainer.setAlignment(Pos.CENTER);

        mCbIsClearNote = new CheckBox();
        hbCheckBoxContainer.getChildren().add(mCbIsClearNote);
        mCbIsClearNote.setText("是否自动清除备注");
        mAdaptUtils.setScaleTextSize(mCbIsClearNote, 25);

        HBox hbBtnCompleteContainer = new HBox();
        vbCenter.getChildren().add(hbBtnCompleteContainer);
        hbBtnCompleteContainer.setAlignment(Pos.CENTER);

        mBtnComplete = new Button();
        hbBtnCompleteContainer.getChildren().add(mBtnComplete);
        mBtnComplete.setText("完成");
        StyleUtils.setTextColor(mBtnComplete, "#ffffff");
        mAdaptUtils.setScaleTextSize(mBtnComplete, 30);
        mAdaptUtils.setScaleSize(mBtnComplete, 200, 60);
        mAdaptUtils.setBackgroundRadius(mBtnComplete, 10);
        mBtnComplete.getStyleClass().add("positive_button");
        mBtnComplete.setCursor(Cursor.HAND);

    }

    private ScanTextFiled getTextFiled(String text, GridPane gpContainer, int index) {
        Label label = new Label();
        gpContainer.add(label, 0, index);
        label.setText(text);
        StyleUtils.setTextColor(label, "#000000");
        mAdaptUtils.setScaleTextSize(label, 20);

        ScanTextFiled scanTextFiled = new ScanTextFiled();
        gpContainer.add(scanTextFiled, 1, index);
        mAdaptUtils.setScaleWidth(scanTextFiled, 400);
        return scanTextFiled;
    }

    private void initLoad() {
        mScanedCodeList = FXCollections.observableArrayList();
        mLastScanedCodeListSize = mApplication.getConfig().getLastScanedCodeListSize(5);
    }

    @Override
    protected Node initContentView() {
        mApContent = new AnchorPane();
        return mApContent;
    }
}
